﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.common.http;
using com.lover.astd.common.manager;

namespace com.lover.astd.common.partner.impl
{
    public class QidianLogin : LoginImplBase
    {
        // 太复杂了, 没法弄, 最后都不知道b_t_s的cookie哪来的
        public QidianLogin() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            string loginurl = String.Format(
                "https://cas.sdo.com/authen/staticLogin.jsonp?callback=staticLogin_JSONPMethod&inputUserId={0}&password={1}&appId=10&areaId=1&serviceUrl=http%3A%2F%2Favd.qidian.com%2FOALoginJump.aspx%3Fqd_skip%3D1%26ReturnUrl%3Dhttp%253A%252F%252Fwww.qidian.com%252FDefault.aspx&productVersion=v5&frameType=3&locale=zh_CN&version=21&tag=20&authenSource=2&productId=2&autoLoginFlag=0&_={2}",
                _username, _password, TimeMgr.TimeStamp);
            HttpResult resp = TransferMgr.doGetPure(loginurl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            string content = resp.getContent();

            if (content.IndexOf("failReason") >= 0)
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }
            Match m = Regex.Match(content, "\"ticket\": \"([^\"]*?)\"");
            if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            string token = m.Groups[1].Value;
            string sso_url = String.Format(
                "http://avd.qidian.com/OALoginJump.aspx?&sitetype=9999&ReturnUrl=http%3A%2F%2Fgame.qidian.com%2Fgame%2FDefault.aspx&ticket={0}",
                token);
            resp = TransferMgr.doGetPure(sso_url, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            sso_url = "http://game.qidian.com/GameAjax.aspx?opName=CheckLoginWithInfo";
            resp = TransferMgr.doPostPure(sso_url, "", ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            sso_url = "http://me.qidian.com/ajax/message.ashx?ajaxMethod=getmessagecentercount&jsonp=GlobalBtn_SdoLoginOut.CallBackUserMsg";
            resp = TransferMgr.doGetPure(sso_url, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }


            gettingSession();
            string token_url = "http://game.qidian.com/game/astd/Login.aspx";
            resp = TransferMgr.doGetPure(token_url, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            content = resp.getContent();
            if (content == null || content.Length == 0){ result.StatusCode = LoginStatusCode.FailInGetToken; return result; }

            string etarget = "", vstate = "", validation = "", hddserver = "", hddServerName = "", hddServerHistory = "", hddNameHistory = "", hddAppArea = "";
            m = Regex.Match(content, "<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"([^'\"]*?)\"");
            if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            vstate = m.Groups[1].Value;
            vstate = Uri.EscapeDataString(vstate);

            m = Regex.Match(content, "<input type=\"hidden\" name=\"__EVENTVALIDATION\" id=\"__EVENTVALIDATION\" value=\"([^'\"]*?)\"");
            if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            validation = m.Groups[1].Value;
            validation = Uri.EscapeDataString(validation);

            string match = String.Format(
                "<a onclick=\"EnterGame\\('([^']*?)','([^']*?)','([^']*?)'\\);\" id=\"[^\"]*?\" class=\"server\" href=\"javascript:__doPostBack\\('([^']*?)','([^']*?)'\\)\">[^\\/]*?{0}区.*?(<\\/b>)*?<\\/a>",
                _acc.ServerId);
            m = Regex.Match(content, match);
            if (m == null || m.Groups == null || m.Groups.Count < 6) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            hddserver = m.Groups[1].Value;
            hddServerName = m.Groups[2].Value;
            hddAppArea = m.Groups[3].Value;
            etarget = m.Groups[4].Value;

            hddserver = Uri.EscapeDataString(hddserver);
            hddServerName = Uri.EscapeDataString(hddServerName);
            hddAppArea = Uri.EscapeDataString(hddAppArea);
            etarget = Uri.EscapeDataString(etarget);

            //m = Regex.Match(content, "");
            //if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            //hddServerHistory = m.Groups[1].Value;

            //m = Regex.Match(content, "");
            //if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            //hddNameHistory = m.Groups[1].Value;

            string data = String.Format(
                "__EVENTTARGET={0}&__EVENTARGUMENT=&__VIEWSTATE={1}&__EVENTVALIDATION={2}&ctl00%24ContentPlaceHolder2%24hddServer={3}&ctl00%24ContentPlaceHolder2%24HiddenField1=&ctl00%24ContentPlaceHolder2%24hddServerName={4}&ctl00%24ContentPlaceHolder2%24hddServerHistory={5}&ctl00%24ContentPlaceHolder2%24hddNameHistory={6}&ctl00%24ContentPlaceHolder2%24hddAppId=&ctl00%24ContentPlaceHolder2%24hddAppArea={7}",
                etarget, vstate, validation, hddserver, hddServerName, hddServerHistory, hddNameHistory, hddAppArea);

            string redirecturl = "http://game.qidian.com/game/astd/Login.aspx";
            resp = TransferMgr.doPostPure(redirecturl, data, ref cookies, "http://game.qidian.com/game/astd/Login.aspx");
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }
            string location = resp.getExtraHeader("Location");
            if (location == null || location.Length == 0) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }

            processStartGame(location, result, ref cookies);
            return result;
        }
    }
}
